package com.example.javawebdemo.dao;

// UserDAOImpl.java (原UserDAO改造为具体实现)

import com.example.javawebdemo.jdbc.JDBCTemplateSingleton;
import com.example.javawebdemo.models.User;
import com.example.javawebdemo.strategy.BCryptHasher;
import com.example.javawebdemo.strategy.PasswordHasher;
import com.example.javawebdemo.utils.PasswordUtils;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;

import java.sql.SQLException;
import java.time.LocalDateTime;

public class UserDAOImpl implements UserDAO {

    private final PasswordHasher passwordHasher = new BCryptHasher();

    private static final RowMapper<User> USER_ROW_MAPPER = (rs, rowNum) -> {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));  // 确保数据库列名与查询语句一致
        user.setEmail(rs.getString("email"));
        user.setPhone(rs.getString("phone"));
        user.setCreatedAt(
                rs.getTimestamp("created_at").toLocalDateTime()  // 时间类型转换
        );
        return user;
    };

    // 原UserDAO所有方法实现粘贴到这里
    @Override
    public boolean registerUser(User user) throws SQLException {
        String sql = "INSERT INTO users (username, password, email, phone, created_at) " +
                "VALUES (?, ?, ?, ?, ?)";
        return JDBCTemplateSingleton.getJdbcTemplate().update(sql,
                user.getUsername(),
                PasswordUtils.hashPassword(user.getPassword()),
                user.getEmail(),
                user.getPhone(),
                LocalDateTime.now()) > 0;
    }


    @Override
    public User findByUsername(String username) throws SQLException {
        String sql = "SELECT id, username, password, email, phone, created_at " +
                "FROM users WHERE username = ?";
        try {
            return JDBCTemplateSingleton.getJdbcTemplate().queryForObject(
                    sql, USER_ROW_MAPPER, username);
        } catch (EmptyResultDataAccessException e) {
            return null; // 查询无结果时返回null
        }
    }
}
